﻿using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Zhaoxi.ReadWriteSeparation.Interface;
using Zhaoxi.ReadWriteSeparation.Model;

namespace Zhaoxi.ReadWriteSeparation.DemoAPIProject.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        #region Identity
        private readonly ILogger<UsersController> _logger;
        private IConfiguration _iConfiguration;
        private IUserService _iUserService;
        public UsersController(ILogger<UsersController> logger, IConfiguration configuration, IUserService iUserService)
        {
            this._logger = logger;
            this._iConfiguration = configuration;
            this._iUserService = iUserService;
        }
        #endregion

        [HttpGet]
        [Route(("test"))]
        public IActionResult New()
        {
            #region 数据插入
            User user = new User()
            {
                Name = "Eleven",
                CompanyId = 1,
                CompanyName = "朝夕教育",
                CreateTime = DateTime.Now,
                CreatorId = 1,
                LastLoginTime = DateTime.Now,
                LastModifierId = 1,
                LastModifyTime = DateTime.Now,
                Password = "123456",
                State = 1,
                Account = "Administrator",
                Email = "57265177@qq.com",
                Mobile = "18664876677",
                UserType = 1
            };
            this._iUserService.InsertUser(user);

            #endregion

            #region 同步时间
            long time = 0;
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                User newUser = null;
                while (newUser == null)
                {
                    Thread.Sleep(100);//因为是同一个context--会有跟踪---find方法
                    newUser = this._iUserService.FindUser(user.Id);//轮询
                }
                stopwatch.Stop();
                time = stopwatch.ElapsedMilliseconds;
            }
            #endregion

            return new JsonResult(new
            {
                User = user,
                Time = time
            });
        }




        // GET: api/<UsersController>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<UsersController>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<UsersController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/<UsersController>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<UsersController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }



    }
}
